<?php

namespace app\api\service;

use app\common\model\PaymentLog as PaymentModel;
use app\common\service\BaseService;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Event;
use think\facade\Log;

class PaySuccess extends BaseService
{

    private  $model;

    // 订单号
    protected  $orderNo;

    public function __construct(string $orderNo)
    {
        parent::__construct();
        $this->orderNo = $orderNo;
        $this->model   = new PaymentModel();
    }

    /**
     * 订单支付成功业务处理
     * @param int $payType
     * @param array $payData
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function onPaySuccess(int $payType, array $payData = []): bool
    {
        Log::channel('wxpay')->info('判断订单支付条件');
        $row = $this->model::where('order_no', $payData['out_trade_no'])->find();
        if ($row->isEmpty()) {
            $this->error = '支付单号不存在';
            return false;
        }
        if ($row->status == PaymentModel::PAY_SUCCESS) {
            $this->error = '已支付';
            return false;
        }
        if ($row->status == PaymentModel::PAY_FAIL) {
            $this->error = '已过期';
            return false;
        }
        Log::channel('wxpay')->info('调用事件PaymentHandle');
        Event::trigger('PaymentHandle', ['payment' => $row->toArray(), 'payType' => $payType, 'trans_id' => $payData['transaction_id']]);
        return true;
    }

    /**
     * @return PaymentModel|array|mixed|\think\Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOrderInfo()
    {
        return $this->model->where('order_no', $this->orderNo)->find();
    }
}